package net.towee.model.impl;

import java.util.List;

import net.towee.model.ProfileArea;
import net.towee.model.ProfileContainer;

/**
 * Implementation of dynamic profile container
 * @author c58
 */
public class ProfileContainerImpl implements ProfileContainer {
	protected List<ProfileArea> profileAreas;
	
	@Override
	public List<ProfileArea> getProfileAreas() {
		return profileAreas;
	}

	@Override
	public ProfileArea getProfileArea(int index) {
		return profileAreas.get(index);
	}

	@Override
	public boolean addProfileArea(ProfileArea area) {
		if(profileAreas.contains(area))
			return false;
		
		profileAreas.add(area);
		return true;
	}

	@Override
	public void removeProfileArea(ProfileArea area) {
		profileAreas.remove(area);
	}

	@Override
	public void addProfileArea(String key, String value) {
		profileAreas.add(new ProfileAreaImpl(key, value));
	}

	@Override
	public void clearExtendedProfile() {
		profileAreas.clear();
	}
	
	@Override
	public String toString() {
		StringBuffer res = new StringBuffer();
		
		for(ProfileArea area : profileAreas) {
			res.append("<area>");
			res.append(area.toString());
			res.append("</area>");
		}
		
		return res.toString();
	}

	@Override
	public void fromString(String str) {
		clearExtendedProfile();
		
		int pos = 0;;
		String name, value;
		
		while( (pos=str.indexOf("<area>", pos)) >= 0) {
			name  = str.substring(pos+6, (pos=str.indexOf("<sep/>", pos)) );
			value = str.substring(pos+6, (pos=str.indexOf("</area>", pos)) );
			pos  += 7;

			addProfileArea(new ProfileAreaImpl(name, value, false));
		}
	}
}
